<template>
	<view class="maintenance-container">
		<view class="filter-section">
			<u-tabs :list="filterList" :current="currentFilter" @change="onFilterChange"></u-tabs>
		</view>

		<view class="device-list">
			<view class="device-item" v-for="(item, index) in deviceList" :key="index">
				<view class="device-info">
					<view class="device-name">{{item.name}}</view>
					<view class="device-address">{{item.address}}</view>
					<view class="filter-info">
						<text class="label">滤芯使用时间：</text>
						<text class="value" :class="{'warning': item.usageDays > 150}">{{item.usageDays}}天</text>
					</view>
					<view class="filter-info">
						<text class="label">剩余寿命：</text>
						<text class="value" :class="{'warning': item.remainingLife < 20}">{{item.remainingLife}}%</text>
					</view>
				</view>
				<view class="device-action">
					<u-button type="primary" size="mini" @click="handleMaintenance(item)">
						预约保养
					</u-button>
				</view>
			</view>
		</view>

		<u-popup v-model="showForm" mode="bottom" border-radius="24">
			<view class="form-popup">
				<view class="form-header">
					<text>预约保养</text>
					<u-icon name="close" size="28" @click="showForm = false"></u-icon>
				</view>
				<view class="form-content">
					<u-form :model="form" ref="uForm">
						<u-form-item label="联系人" prop="name" required>
							<u-input v-model="form.name" placeholder="请输入联系人姓名"></u-input>
						</u-form-item>
						<u-form-item label="联系电话" prop="phone" required>
							<u-input v-model="form.phone" placeholder="请输入联系电话"></u-input>
						</u-form-item>
						<u-form-item label="预约时间" prop="appointmentTime" required>
							<view class="selected-time" @click="showTimePicker = true">
								{{form.appointmentTime ? formatTime(form.appointmentTime) : '请选择预约时间'}}
							</view>
							<u-datetime-picker
								v-model="form.appointmentTime"
								:show="showTimePicker"
								@confirm="onTimeSelect"
								@cancel="showTimePicker = false"
								mode="datetime"
								:min-date="minDate"
								:max-date="maxDate"
							></u-datetime-picker>
						</u-form-item>
						<u-form-item label="备注" prop="remark">
							<u-textarea v-model="form.remark" placeholder="请输入备注信息（选填）"></u-textarea>
						</u-form-item>
					</u-form>
				</view>
				<view class="form-footer">
					<u-button type="primary" @click="submitForm">提交预约</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		const currentDate = new Date()
		const maxDate = new Date('2035-12-31') // 设置最大时间到2035年底
		return {
			currentFilter: 0,
			filterList: [{
				name: '全部'
			}, {
				name: '需要保养'
			}, {
				name: '正常'
			}],
			deviceList: [{
				id: 1,
				name: '净水器 A1001',
				address: '北京市朝阳区xxx小区1号楼101',
				usageDays: 160,
				remainingLife: 15
			}, {
				id: 2,
				name: '净水器 A1002',
				address: '北京市朝阳区xxx小区2号楼202',
				usageDays: 90,
				remainingLife: 55
			}, {
				id: 3,
				name: '净水器 A1003',
				address: '北京市朝阳区xxx小区3号楼303',
				usageDays: 30,
				remainingLife: 85
			}],
			showForm: false,
			showTimePicker: false,
			minDate: currentDate.getTime(),
			maxDate: maxDate.getTime(),
			form: {
				name: '',
				phone: '',
				appointmentTime: currentDate.getTime(), // 设置初始时间为当前时间
				remark: '',
				deviceId: null
			},
			rules: {
				name: [{
					required: true,
					message: '请输入联系人姓名',
					trigger: ['blur', 'change']
				}],
				phone: [{
					required: true,
					message: '请输入联系电话',
					trigger: ['blur', 'change']
				}],
				appointmentTime: [{
					required: true,
					message: '请选择预约时间',
					trigger: ['blur', 'change']
				}]
			}
		}
	},
	methods: {
		onTimeSelect(timestamp) {
			console.log(timestamp, 'timestamp');
			// timestamp 已经是时间戳，直接赋值给 appointmentTime
			this.form.appointmentTime = timestamp.value;
			this.showTimePicker = false;
		},
		formatTime(time) {
			if (!time) return '';
			const date = new Date(Number(time));
			if (isNaN(date.getTime())) return '';
			
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}`;
		},
		onFilterChange(index) {
			this.currentFilter = index
			// 根据筛选条件更新设备列表
			// TODO: 实现筛选逻辑
		},
		handleMaintenance(device) {
			this.form.deviceId = device.id
			this.showForm = true
		},
	
		submitForm() {
			this.$refs.uForm.validate(valid => {
				if (valid) {
					uni.showLoading({
						title: '提交中...'
					})
					
					// 模拟提交
					setTimeout(() => {
						uni.hideLoading()
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						
						this.showForm = false
						// 重置表单
						this.form = {
							name: '',
							phone: '',
							appointmentTime: '',
							remark: '',
							deviceId: null
						}
					}, 2000)
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.maintenance-container {
	min-height: 100vh;
	background-color: #f5f5f5;

	.filter-section {
		background-color: #fff;
		position: sticky;
		top: 0;
		z-index: 1;
	}

	.device-list {
		padding: 20rpx;

		.device-item {
			background-color: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.device-info {
				flex: 1;

				.device-name {
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
				}

				.device-address {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 10rpx;
				}

				.filter-info {
					font-size: 28rpx;
					margin-bottom: 6rpx;

					.label {
						color: #666;
					}

					.value {
						color: #333;

						&.warning {
							color: #ff4d4f;
						}
					}
				}
			}

			.device-action {
				margin-left: 20rpx;
			}
		}
	}

	.form-popup {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding: 30rpx;

		.form-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			text {
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.form-content {
			.selected-time {
				height: 70rpx;
				line-height: 70rpx;
				padding: 0 20rpx;
				background-color: #f5f5f5;
				border-radius: 8rpx;
				color: #333;
			}
		}

		.form-footer {
			margin-top: 40rpx;
		}
	}
}
</style>
